package com.zoe.onelink.core.encryptor;

import com.zoe.onelink.annotation.data.encryptor.IEncryptor;
import com.zoe.onelink.core.encryptor.algorithm.RsaEncryptFieldAlgorithm;
import com.zoe.onelink.core.encryptor.algorithm.Sm2EncryptFieldAlgorithm;
import com.zoe.onelink.core.encryptor.algorithm.Sm4EncryptFieldAlgorithm;
import com.zoe.onelink.core.property.EncryptKeyPair;
import com.zoe.onelink.core.property.OnelinkProperties;
import com.zoe.onelink.annotation.data.encryptor.enumeration.Algorithm;
import lombok.NonNull;

import java.util.Map;

/**
 * <p>标题: 加密算法实例工厂</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-11-12
 */
public class EncryptorFactory {

    private static EncryptorFactory self;

    private final OnelinkProperties onelinkProperties;
    private final Map<String, EncryptKeyPair> keyPairs;

    public EncryptorFactory(OnelinkProperties onelinkProperties) {
        this.onelinkProperties = onelinkProperties;
        this.keyPairs = onelinkProperties.getWeb().getEncrypt().getKeyPairs();
        self = this;
    }


    /**
     * 创建算法实例
     *
     * @param algorithm 算法名称
     */
    public static IEncryptor createEncryptor(@NonNull Algorithm algorithm) {
        EncryptKeyPair encryptKeyPair = self.keyPairs.get(algorithm.name());
        IEncryptor encryptor;
        switch (algorithm) {
            case SM2:
                encryptor = new Sm2EncryptFieldAlgorithm(self.onelinkProperties, encryptKeyPair);
                break;
            case SM4:
                encryptor = new Sm4EncryptFieldAlgorithm(self.onelinkProperties, encryptKeyPair);
                break;
            case RSA:
                encryptor = new RsaEncryptFieldAlgorithm(self.onelinkProperties, encryptKeyPair);
            default:
                encryptor = null;
        }
        return encryptor;
    }

}
